﻿$(document).ready(function () {
    var table = $("#slotPicker");
    var data = $.parseJSON($("#" + dataID).val());

    table.html("");
    var dates = $("<tr>" +
                    "<td rowspan='2'>&nbsp;</td>" +
                  "</tr>");
    var amPms = $("<tr></tr>");
    var columns = data.AvailableDates.length + 1;
    $.each(data.AvailableDates, function (index, availableDate) {
        var date = $("<td colspan='2' class='GridBg'>" + (new Date(parseInt(availableDate.substr(6)))).format("mmm dd") + "</td>");
        dates.append(date);
    });
    table.append(dates);

    for (var i = 0; i < (columns - 1) * 2; i++) {
        if ((i % 2) == 0) amPms.append("<td class='GridBg'>AM</td>");
        if ((i % 2) == 1) amPms.append("<td class='GridBg'>PM</td>");
    };
    table.append(amPms);

    $.each(data.Resources, function (index, resource) {
        var resourceRow = $("<tr></tr>");
        resourceRow.append("<td class='GridBg'>" + resource.Name + "</td>")
        $.each(data.AvailableDates, function (index, availableDate) {
            var date = (new Date(parseInt(availableDate.substr(6))));
            var currentDate = new Date(date.getYear(), date.getMonth(), date.getUTCDate(),0,0,0)
            var am = new Date(date.getYear(), date.getMonth(), date.getUTCDate(),12,0,0);
            var pm = new Date(date.getYear(), date.getMonth(), date.getUTCDate(),24, 0, 0);
            var amCount = "<td>&nbsp;</td>";
            var pmCount = "<td>&nbsp;</td>";
            $.each(resource.AvailableCount, function (index, availableCount) {
                var startDate = (new Date(parseInt(availableCount.Key.startDate.substr(6))));
                var endDate = (new Date(parseInt(availableCount.Key.endDate.substr(6))));

                if (endDate >= currentDate && endDate <= am) {
                    amCount = "<td><a href='#'>" + availableCount.Value + "</a></td>";
                }
                if (endDate >= am && endDate < pm) {
                    pmCount = "<td><a href='#'>" + availableCount.Value + "</a></td>";
                }
            });
            resourceRow.append(amCount);
            resourceRow.append(pmCount);
        });

        table.append(resourceRow);
    });
});
